define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'sound/index',
                    add_url: 'sound/add',
                    edit_url: 'sound/edit',
                    del_url: 'sound/del',
                    multi_url: 'sound/multi',
                    table: 'sound',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                pageSize: 20,
                pageList: [20, 50],
                showExport: false,
                exportTypes: ['excel'],
                clickToSelect: false,
                dblClickToEdit: false,
                singleSelect: false,
                showColumns: false,
                columns: [
                    [{
                            checkbox: true
                        },
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        //{field: 'admin_id', title: __('Admin_id')},
                        {
                            field: 'admin.nickname',
                            title: __('Admin_id'),
                            // formatter: Table.api.formatter.flag,
                            visible: requirejs.s.contexts._.config.config.admined
                        },
                        {
                            field: 'name',
                            title: __('Name')
                        },
                        // {
                        //     field: 'type',
                        //     title: __('Type'),
                        //     visible: false,
                        //     searchList: {"ivr": __('type ivr'), "queue": __('type queue')}
                        // },
                        // {
                        //     field: 'type_text',
                        //     title: __('Type')
                        // },
                        {
                            field: 'file',
                            title: __('File'),
                            operate: false,
                            formatter: function (value, row, index) {
                                if(row.tts =="-1"){
                                    return '<div class="input-group input-group-sm" style="width:136px;margin:0 auto;"><input type="text" class="form-control input-sm" value="播放该语音文件" readonly="readonly"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm btn-playback"><i class="fa fa-play"></i></a></span></div>';     
                                }else{
                                    return row.content;
                                }
                            },
                            events: {
                                'click .btn-playback': function (e, value, row, index) {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    var audio_playback = document.getElementById('audio_playback');
                                    audio_playback.pause();
                                    audio_playback.src = value;
                                    audio_playback.currentTime = 0;
                                    if ($(this).find('i').hasClass('fa-play')) {
                                        audio_playback.play();
                                        $('.btn-playback').find('i').removeClass('fa-pause').addClass('fa-play');
                                        $(this).find('i').addClass('fa-pause').removeClass('fa-play');
                                    } else {
                                        audio_playback.pause();
                                        $('.btn-playback').find('i').removeClass('fa-pause').addClass('fa-play');
                                        $(this).find('i').addClass('fa-play').removeClass('fa-pause');
                                    }
                                },
                            }
                        },
                        // {
                        //     field: 'file_size',
                        //     title: __('File_size')
                        // },
                        // {
                        //     field: 'file_format',
                        //     title: __('File_format')
                        // },
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'status',
                            title: __('审核状态'),
                            table: table,
                            // operate: false,
                            formatter: function (value, row, index) {
                                var table = this.table;
                                // 操作配置
                                var options = table ? table.bootstrapTable('getOptions') : {};
                                var buttons = [];
                                if (value == 0) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-circle-o',
                                        title: __('待审核'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-staty',
                                        url: options.extend.start_task_url
                                    });
                                } else if (value == 1) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-check-circle-o',
                                        title: __('审核通过'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-staty',
                                        url: options.extend.start_task_url
                                    });
                                } else if (value == -1) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-times-circle-o',
                                        title: __('审核失败'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-staty',
                                        url: options.extend.start_task_url
                                    });
                                }
                                return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
                                return value;
                            },
                            events: {
                                'click .btn-staty': function (e, value, row, index) {
                                    var that = this;
                                    var $that = $(this);
                                    // console.log( $('.status').text())
                                    if ($('.status').text() === '1') {
                                        layer.open({
                                            content: '是否通过审核?',
                                            btn: ['是', '否'],
                                            title: '温馨提示',
                                            btn1: function (index, layero) {
                                                $.post("/admin/sound/status/id/" + row.id + "/status/1", {
                                                    id: row.id
                                                }, function (data) {
                                                    layer.close(index);
                                                    if (data == "1") {
                                                        $that.attr('data-original-title', '审核通过')
                                                        $that.find('i').addClass('fa-check-circle-o').removeClass('fa-circle-o,fa-times-circle-o');
                                                        Toastr.success("审核通过！");
                                                        table.bootstrapTable('refresh');
                                                    }
                                                });
                                            },
                                            btn2: function (index, layero) {
                                                $.post("/admin/sound/status/id/" + row.id + "/status/-1", {
                                                    id: row.id
                                                }, function (data) {
                                                    layer.close(index);
                                                    if (data == "1") {
                                                        $that.attr('data-original-title', '审核失败')
                                                        $that.find('i').addClass('fa-times-circle-o').removeClass('fa-circle-o,fa-check-circle-o');
                                                        Toastr.success("审核不通过！");
                                                        table.bootstrapTable('refresh');
                                                    }
                                                });
                                            }
                                        });
                                    }
                                }
                            }
                        },
                        {
                            field: 'tts',
                            title: __('tts'),
                            visible: false
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });
            $('#audio_playback').on('ended', function () {
                $('.btn-playback').find('i').removeClass('fa-pause').addClass('fa-play');
            });
            if ($('.status').text() != '1') {
                $('.status').attr('disabled', 'true');
                //$that.attr('disabled',"true")
            }
            $('.btn-singlesearch').on('click', function () {
                $('.form-control[name="callstate"]').val("success");
                $('.form-control[name="status"]').val("")
                $('.btn-info[type="submit"]').trigger('click');
            });
            $('.btn-singlesearcha').on('click', function () {
                $('.form-control[name="callstate"]').val("success");
                $('.form-control[name="status"]').val("1")
                $('.btn-info[type="submit"]').trigger('click');
                // Toastr.success("已审核搜索成功");
            });
            $('.btn-singlesearchb').on('click', function () {
                $('.form-control[name="callstate"]').val("success");
                $('.form-control[name="status"]').val("0")
                $('.btn-info[type="submit"]').trigger('click');
                // Toastr.success("待审核搜索成功");
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            var audio_context;
            var recorder;
            function startUserMedia(stream) {
                var input = audio_context.createMediaStreamSource(stream);
                recorder = new Recorder(input);
            }
            $('#record-file').click(function () {
                if ($(this).find('i').hasClass('fa-microphone')) {
                    $(this).removeClass('btn-info').removeClass('btn-danger').addClass('btn-danger');
                    $(this).find('i').removeClass('fa-pause').removeClass('fa-microphone').addClass('fa-pause');
                    $(this).find('span').html('停止');
                    recorder && recorder.record();
                } else {
                    $(this).removeClass('btn-info').removeClass('btn-danger').addClass('btn-info');
                    $(this).find('i').removeClass('fa-pause').removeClass('fa-microphone').addClass('fa-microphone');
                    $(this).find('span').html('录制');
                    recorder && recorder.stop();
                    recorder && recorder.exportWAV(function (blob) {
                        window.Upload.list['plupload-file'].addFile(blob, '' + new Date().toISOString() + '.wav');
                    });
                    recorder.clear();
                }
            });
            try {
                // webkit shim
                window.AudioContext = window.AudioContext || window.webkitAudioContext;
                navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
                window.URL = window.URL || window.webkitURL;
                audio_context = new AudioContext();

            } catch (e) {
                alert('No web audio support in this browser!');
            }
            navigator.getUserMedia({
                audio: true
            }, startUserMedia, function (e) {
                alert('No live audio input: ' + e);
            });
            $(".guide-btn input[type='checkbox']").click(function () {
                if ($('.guide-btn input[type="checkbox"]:checked').val() != null) {
                    $('.guide').hide();
                    $('.synthesis').show();
                    $('#c-file').val('');
                } else {
                    $('.guide').show();
                    $('.synthesis').hide();
                    $('.synthesis textarea').html('');
                }
            });
            $(document).on("click", ".btn-default", function () {
                $('.guide').show();
                $('.synthesis').hide();
            });
        },
        edit: function () {
            Controller.api.bindevent();
            var audio_context;
            var recorder;
            function startUserMedia(stream) {
                var input = audio_context.createMediaStreamSource(stream);
                recorder = new Recorder(input);
            }
            $('#record-file').click(function () {
                if ($(this).find('i').hasClass('fa-microphone')) {
                    $(this).removeClass('btn-info').removeClass('btn-danger').addClass('btn-danger');
                    $(this).find('i').removeClass('fa-pause').removeClass('fa-microphone').addClass('fa-pause');
                    $(this).find('span').html('停止');
                    recorder && recorder.record();
                } else {
                    $(this).removeClass('btn-info').removeClass('btn-danger').addClass('btn-info');
                    $(this).find('i').removeClass('fa-pause').removeClass('fa-microphone').addClass('fa-microphone');
                    $(this).find('span').html('录制');
                    recorder && recorder.stop();
                    recorder && recorder.exportWAV(function (blob) {
                        window.Upload.list['plupload-file'].addFile(blob, '' + new Date().toISOString() + '.wav');
                    });
                    recorder.clear();
                }
            });
            try {
                // webkit shim
                window.AudioContext = window.AudioContext || window.webkitAudioContext;
                navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
                window.URL = window.URL || window.webkitURL;
                audio_context = new AudioContext();

            } catch (e) {
                alert('No web audio support in this browser!');
            }
            navigator.getUserMedia({
                audio: true
            }, startUserMedia, function (e) {
                alert('No live audio input: ' + e);
            });
            
       	    var $radioTts=$('.guide-btn input[type="radio"]');
		var filed_v=$('#c-file').val();
		var content_h=$('.synthesis textarea').html();
	    if($radioTts.val() ==-1){
		$('.guide').show();
		$('.synthesis').hide();
		$(".guide-btn input[type='checkbox']").attr('checked',false);
	    }else{
		$('.guide').hide();
		$('.synthesis').show();
		$(".guide-btn input[type='checkbox']").attr('checked',true);
	    }
	   $(".guide-btn input[type='checkbox']").click(function () {
	   var val = $('.guide-btn input[type="checkbox"]:checked').val();
	   if (val != null) {
	        $('.guide').hide();
		$('.synthesis').show();
	   } else {
		$('.guide').show();
		$('.synthesis').hide();
	 }
	});
	$(document).on("click", ".btn-default", function () {
	if($radioTts.val() ==-1){
	$('.guide').show();
	$('.synthesis').hide();
	$(".guide-btn input[type='checkbox']").attr('checked',false);
	$('#c-file').val(filed_v);
	}else{
	$('.guide').hide();
	$('.synthesis').show();
	$(".guide-btn input[type='checkbox']").attr('checked',true);
	$('.synthesis textarea').html(content_h);
	}
	});   
		
	 },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    }

    return Controller;
});
